package zhjb.platform.module.blog.action;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import zhjb.platform.dao.DCriteriaPageSupport;
import zhjb.platform.module.blog.bean.BlogBase;
import zhjb.platform.module.blog.bean.BlogComment;
import zhjb.platform.module.blog.bean.BlogContent;
import zhjb.platform.module.blog.bean.Classify;
import zhjb.platform.module.blog.bean.ShowBlog;
import zhjb.platform.module.blog.service.BlogService;
import zhjb.platform.module.blog.service.ClassifyService;
import zhjb.platform.util.SpringUtil;
import zhjb.platform.web.BaseAction;
import zhjb.platform.web.module.system.bean.User;
import zhjb.platform.web.module.system.service.UserService;

import com.opensymphony.xwork2.Action;

/**
 * 博客管理
 * 
 * @author zhangjianbing@msn.com
 * 
 */
public class BlogAction extends BaseAction {
	private BlogBase base;
	private BlogContent content;
	private BlogService blogService = (BlogService) SpringUtil.getWebApplicationContext().getBean("blogService");
	private UserService userService = (UserService) SpringUtil.getWebApplicationContext().getBean("userService");
	private ClassifyService classifyService = (ClassifyService) SpringUtil.getWebApplicationContext().getBean("classifyService");
	private File file = null;
	private List<User> users;
	private List<Classify> classies;
	private User user;
	private String message;
	private String bgImag;
	/** 草稿 */
	private List<BlogBase> cgList;
	private List<ShowBlog> left;
	private List<ShowBlog> right;
	private List<BlogBase> blogList;
	/** 评论内容 */
	private String commont;
	/** 所有评论 */
	private List<BlogComment> blogComments;

	/**
	 * 进入首页
	 * 
	 * @return
	 */
	public String frontIndex() {
		users = userService.findAllUser();
		classies = classifyService.getAllClassifies(null);
		DCriteriaPageSupport<ShowBlog> showBlogs = blogService.findShowBlog(page == 0 ? 1 : page, pageSize);
		total = showBlogs.getTotalCount();
		left = new ArrayList<ShowBlog>();
		right = new ArrayList<ShowBlog>();
		long leftcount = 0;
		long rightcount = 0;
		for (int i = 0; i < showBlogs.size(); i++) {
			if (leftcount <= rightcount) {
				left.add(showBlogs.get(i));
				leftcount += showBlogs.get(i).getShowContent().length();
			} else {
				right.add(showBlogs.get(i));
				rightcount += showBlogs.get(i).getShowContent().length();
			}
		}
		return Action.SUCCESS;
	}

	public String index() {
		classies = classifyService.getAllClassifies(null);
		cgList = blogService.findAllCG();
		return Action.SUCCESS;
	}

	/**
	 * 跳转到登陆页
	 * 
	 * @return
	 */
	public String frontLogin() {
		long name = System.currentTimeMillis() % 12;
		bgImag = (name + 1) + ".jpg";
		return Action.SUCCESS;
	}

	/**
	 * 博客登录
	 * 
	 * @return
	 */
	public String blogLogin() {
		user = userService.login(user.getUsername(), user.getUserpwd());
		if (user != null) {
			request.getSession().setAttribute("frontuser", user);
			return Action.SUCCESS;
		} else {
			message = "用户名或密码错误，请重新登录。";
			return Action.INPUT;
		}
	}

	/**
	 * 前台退出
	 * 
	 * @return
	 */
	public String logout() {
		HttpSession session = request.getSession();
		request.getSession().removeAttribute("frontuser");
		session.setMaxInactiveInterval(1);
		return Action.SUCCESS;
	}

	/**
	 * 保存草稿
	 * 
	 * @throws FException
	 */
	public void saveCG() throws Exception {
		HttpSession session = request.getSession();
		Object user = session.getAttribute("frontuser");
		base.setAuthor(user == null ? "admin" : ((User) user).getUsername());
		String contentString = content.getContent();
		Document doc = Jsoup.parseBodyFragment(contentString);
		Elements eles = doc.body().select("h3");
		String title = "无标题";
		if (eles != null && !eles.isEmpty()) {
			Element etitle = eles.get(0);
			title = etitle.text();
		}
		base.setTitle(title);
		blogService.saveOrUpdate(base, content, 0);
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
			if (out != null) {
				out.write(base.getId() + "," + content.getId());
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}

	/**
	 * 发布
	 * 
	 * @throws Exception
	 */
	public void publish() throws Exception {
		HttpSession session = request.getSession();
		Object user = session.getAttribute("frontuser");
		base.setAuthor(user == null ? "admin" : ((User) user).getUsername());
		String contentString = content.getContent();
		Document doc = Jsoup.parseBodyFragment(contentString);
		Elements eles = doc.body().select("h3");
		String title = "无标题";
		if (eles != null && !eles.isEmpty()) {
			Element etitle = eles.get(0);
			title = etitle.text();
		}
		base.setTitle(title);
		blogService.saveOrUpdate(base, content, 1);
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
			if (out != null) {
				out.write(base.getId());
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}

	/**
	 * 加载草稿
	 * 
	 * @return
	 */
	public String loadcg() {
		base = blogService.loadCgBase(base.getId());
		content = blogService.loadCgContent(base.getId());
		index();
		return Action.SUCCESS;
	}

	public String show() {
		base = blogService.show(base.getId());
		content = blogService.showContent(base.getId());
		String contentString = content.getContent();
		Document doc = Jsoup.parseBodyFragment(contentString);
		Element body = doc.body();
		Elements eles = body.select("h3");
		Elements peles = body.select("p");
		if (peles != null && !peles.isEmpty()) {
			for (Element ele : peles) {
				ele.removeAttr("style");
				ele.removeAttr("class");
			}
		}
		if (eles != null && !eles.isEmpty()) {
			eles.get(0).remove();
			contentString = body.html();
		}
		content = new BlogContent();
		content.setContent(contentString);
		return Action.SUCCESS;
	}

	/**
	 * 博客管理后台
	 * 
	 * @return
	 */
	public String artList() {
		blogList = blogService.blogBaseList(page, pageSize);
		return Action.SUCCESS;
	}

	/**
	 * 提交留言评论
	 * 
	 * @return
	 */
	public String putCommonts() {
		String flag = "1";
		if (commont != null && commont.trim().length() > 0 && commont.length() <= 300 && base != null && base.getId() != null && base.getId().length() > 0) {
			String userIp = request.getRemoteAddr();
			blogService.addCommont(commont, userIp, base.getId());
		} else {
			flag = "-1";
		}

		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
			if (out != null) {
				out.write(flag);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				out.close();
			}
		}
		return null;
	}

	/**
	 * 删除一片博客
	 * 
	 * @return
	 */
	public String deleteBolg() {
		String flag = "1";
		String id = base.getId();
		if (id != null && id.length() > 0) {
			boolean isOk = true;
			String upperId = id.toUpperCase();
			for (int i = 0; i < upperId.length(); i++) {
				char c = upperId.charAt(i);
				if (!((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F'))) {
					isOk = false;
				}
			}
			if (isOk) {
				blogService.deleteBolg(base.getId());
			} else {
				flag = "-1";
			}
		} else {
			flag = "-1";
		}
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
			if (out != null) {
				out.write(flag);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				out.close();
			}
		}
		return null;
	}

	/**
	 * 上传文件
	 */
	public void upload() {

	}

	public BlogBase getBase() {
		return base;
	}

	public void setBase(BlogBase base) {
		this.base = base;
	}

	public BlogContent getContent() {
		return content;
	}

	public void setContent(BlogContent content) {
		this.content = content;
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public List<User> getUsers() {
		return users;
	}

	public void setUsers(List<User> users) {
		this.users = users;
	}

	public List<Classify> getClassies() {
		return classies;
	}

	public void setClassies(List<Classify> classies) {
		this.classies = classies;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public String getBgImag() {
		return bgImag;
	}

	public void setBgImag(String bgImag) {
		this.bgImag = bgImag;
	}

	public List<BlogBase> getCgList() {
		return cgList;
	}

	public void setCgList(List<BlogBase> cgList) {
		this.cgList = cgList;
	}

	public List<ShowBlog> getLeft() {
		return left;
	}

	public void setLeft(List<ShowBlog> left) {
		this.left = left;
	}

	public List<ShowBlog> getRight() {
		return right;
	}

	public void setRight(List<ShowBlog> right) {
		this.right = right;
	}

	public List<BlogBase> getBlogList() {
		return blogList;
	}

	public void setBlogList(List<BlogBase> blogList) {
		this.blogList = blogList;
	}

	public String getCommont() {
		return commont;
	}

	public void setCommont(String commont) {
		this.commont = commont;
	}

	public List<BlogComment> getBlogComments() {
		return blogComments;
	}

	public void setBlogComments(List<BlogComment> blogComments) {
		this.blogComments = blogComments;
	}

}
